package com.invengo.module_check.ui.fragment.revoke;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.invengo.base.utils.BeanMapperUtils;
import com.invengo.library_db.entity.module_check.BookBean;
import com.invengo.library_rfid.classify.AnalyzeImpl;
import com.invengo.library_rfid.classify.RFIDCallBackListener;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.BR;
import com.invengo.module_check.R;
import com.invengo.module_check.data.repsitory.business.BusinessRepsitory;
import com.invengo.module_check.ui.fragment.revoke.item.RevokeItemViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import java8.util.stream.StreamSupport;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class RevokeViewModel extends BaseViewModel<BusinessRepsitory> {
    public RFIDCallBackListener rfidService = new RFIDCallBackListener(AnalyzeImpl.TO_BOOK, tagInfo -> onScanResult(tagInfo), state -> isReading.set(state));
    public BindingRecyclerViewAdapter adapter = new BindingRecyclerViewAdapter();

    //    =====================这部分是撤销强制定位=========================
    public ObservableList<RevokeItemViewModel> byRevokeItemList = new ObservableArrayList<>();
    public ItemBinding<RevokeItemViewModel> byRevokeitemBinding = ItemBinding.of(BR.viewModel, R.layout.item_force_revoke);

    public RevokeViewModel(@NonNull Application application) {
        super(application, BusinessRepsitory.getInstance());
        registerRFID(rfidService);
    }

    public void onScanResult(TagInfo tagInfo) {
        switch (tagInfo.getRfidModel()) {
            case TID:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
//                    getShelfByTid(tagInfo.getTag());
                } else
                    getBookByTid(tagInfo.getTag());
                break;
            case EPC:
            case U_DATA:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
//                    getShelfByCode(tagInfo.getTag());
                } else
                    getBookByCode(tagInfo.getTag());
                break;
        }
    }

    public UIChangeObservable ui = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent<List<BookBean>> nextEvent = new SingleLiveEvent<>();
    }

    public int getPosition(ItemViewModel item) {
        return byRevokeItemList.indexOf(item);
    }

    /**
     * 撤销强制定位
     */
    public BindingCommand revokeForce = new BindingCommand(() -> {
        forceRevokeBook();
    });
    /**
     * 清除所有数据
     */
    public BindingCommand cleanAllData = new BindingCommand(() -> {
        cleanRFIDCacheNotStop();
        byRevokeItemList.clear();
    });

    /**
     * 按Tid查询书本
     *
     * @param tid 标签
     */
    private void getBookByTid(String tid) {
        model.getBookByTid(tid)
                .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                .subscribe(bookBean -> addItem(bookBean));
    }

    /**
     * 按Tid查询书本
     *
     * @param code 标签
     */
    private void getBookByCode(String code) {
        model.getBookByCode(code)
                .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                .subscribe(bookBean -> addItem(bookBean));
    }


    /**
     * 强制撤销定位
     */
    private void forceRevokeBook() {
        List<BookBean> matchBooks = BeanMapperUtils.cloneList(getMatchBooks());
        model.forceRevokeBook(matchBooks)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(updateResult -> {
                    ToastUtils.showShort(updateResult.getAffactNum() + "条数据撤销强制定位成功");
                    stopScan();
                    cleanAllData.execute();
                    refreshBooks(matchBooks);
//                    ui.nextEvent.postValue(BeanMapperUtils.cloneList(matchBooks));
                }, throwable -> {
                    KLog.e("------------"+throwable.getMessage());
                    stopScan();
                    cleanAllData.execute();
                    ui.nextEvent.postValue(null);
                });
    }

    private void refreshBooks(List<BookBean> beans) {
        List<BookBean> tempBeans = new ArrayList<>();
        for (BookBean bean : beans) {
            model.getBookByTid(bean.getTid())
                    .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                    .subscribe(bookBean -> {
                        tempBeans.add(bookBean);
                        if (tempBeans.size() == beans.size()) {
                            ui.nextEvent.postValue(tempBeans);
                        }
                    });
        }
    }


    /**
     * 添加项目
     *
     * @param bean 豆
     */

    private void addItem(BookBean bean) {
        byRevokeItemList.add(new RevokeItemViewModel(this, bean));
    }

    /**
     * 删除项时
     */
    public void onItemRemove(ItemViewModel item) {
        int position = 0;
        position = byRevokeItemList.indexOf(item);
        byRevokeItemList.remove(position);
        adapter.notifyDataSetChanged();
        ToastUtils.showShort("删除成功");
    }

    private List<BookBean> getMatchBooks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return byRevokeItemList.stream()
                    .map(viewModel -> viewModel.book.getValue()).collect(Collectors.toList());
        }else{
            return StreamSupport.stream(byRevokeItemList)
                    .map(viewModel -> viewModel.book.getValue()).collect(java8.util.stream.Collectors.toList());
        }
    }


}
